package com.ym.jiujiangeyou.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * @author 叶铭
 * @Description: 下载工具类
 */
public class DownloadUtils {
	private static final int CONNECT_TIMEOUT = 10000;
	private static final int DATA_TIMEOUT = 40000;
	private final static int DATA_BUFFER = 8192;

	/**
	 * @author 叶铭
	 * @Description: 下载回调接口
	 */
	public interface DownloadListener {
		/** 
		* @param progress  进度
		* @retur  void 
		* @Description: 下载中， progress更新参数
		*/
		public void downloading(int progress);

		/** 
		*   
		* @retur  void 
		* @Description: 下载完成
		*/
		public void downloaded();
	}

	/** 
	* @param url 下载url
	* @param file 文件
	* @param append  boolean
	* @param downloadListener  监听器
	* @return
	* @throws Exception  
	* @retur  long 文件大小
	* @Description: 下载
	*/
	public static long download(String url, File file, boolean append,
			DownloadListener downloadListener) throws Exception {
		int downloadProgress = 0;
		long remoteSize = 0;
		int currentSize = 0;
		long totalSize = -1;

		if (!append && file.exists() && file.isFile()) {
			file.delete();
		}

		if (append && file.exists() && file.exists()) {
			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				currentSize = fis.available();
			} catch (IOException e) {
				throw e;
			} finally {
				if (fis != null) {
					fis.close();
				}
			}
		}

		HttpGet request = new HttpGet(url);

		if (currentSize > 0) {
			request.addHeader("RANGE", "bytes=" + currentSize + "-");
		}

		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
		HttpConnectionParams.setSoTimeout(params, DATA_TIMEOUT);
		HttpClient httpClient = new DefaultHttpClient(params);

		InputStream is = null;
		FileOutputStream os = null;
		try {
			HttpResponse response = httpClient.execute(request);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				is = response.getEntity().getContent();
				remoteSize = response.getEntity().getContentLength();
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					is = new GZIPInputStream(is);
				}
				os = new FileOutputStream(file, append);
				byte buffer[] = new byte[DATA_BUFFER];
				int readSize = 0;
				while ((readSize = is.read(buffer)) > 0) {
					os.write(buffer, 0, readSize);
					os.flush();
					totalSize += readSize;
					if (downloadListener != null) {
						downloadProgress = (int) (totalSize * 100 / remoteSize);
						if (downloadProgress > 0 && downloadProgress % 5 == 0) {
							// System.out.println("-------------2--downloadProgress-----"+downloadProgress)
							// ;
							downloadListener.downloading(downloadProgress);
						}

					}
				}
				// System.out.println("-------------2--totalSize-----"+totalSize)
				// ;
				if (totalSize < 0) {
					totalSize = 0;
				}
			}
		} finally {
			if (os != null) {
				os.close();
			}
			if (is != null) {
				is.close();
			}
		}

		if (totalSize < 0) {
			throw new Exception("Download file fail: " + url);
		}

		if (downloadListener != null) {
			downloadListener.downloaded();
		}

		return totalSize;
	}
}
